// 按钮权限指令
import useLoginStore from '@/stores/login-store'
import {nextTick} from 'vue'

export const checkPermission = {
    beforeMount(el, binding) {
        const {value} = binding
        const permissions = useLoginStore().userInfo.roleAndPermissions || []
        if (value && value instanceof Array) {
            if (value.length) {
                const permissionRoles = value
                const hasPermission = permissions.some(role => {
                    return permissionRoles.includes(role)
                })
                // 没有权限 移除Dom元素 判断太快，尚未加载dom,会检测失败，因此需要套一个nextTick
                nextTick(() => {
                    if ( !hasPermission) {
                        el.parentNode && el.parentNode.removeChild(el)
                    }
                }).then()
            }
        } else {
            throw new Error('need permission! Like v-permission="[\'admin\',\'editor\']"')
        }
    }
}

